'use client';

import React, { useState, useCallback } from 'react';
import { parseExcelFile, type ParsedExcelFile, type ExcelData } from '@/lib/excel-parser.client';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Upload, FileSpreadsheet, Eye, Download } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

interface ExcelViewerProps {
  initialData?: ParsedExcelFile;
}

export default function ExcelViewer({ initialData }: ExcelViewerProps) {
  const [excelData, setExcelData] = useState<ParsedExcelFile | null>(initialData || null);
  const [loading, setLoading] = useState(false);
  const [dragOver, setDragOver] = useState(false);

  const handleFileUpload = useCallback(async (file: File) => {
    if (!file.name.match(/\.(xlsx|xls)$/i)) {
      alert('请选择Excel文件 (.xlsx 或 .xls)');
      return;
    }

    setLoading(true);
    try {
      const parsedData = await parseExcelFile(file);
      setExcelData(parsedData);
    } catch (error) {
      console.error('解析Excel文件失败:', error);
      alert('解析Excel文件失败，请检查文件格式');
    } finally {
      setLoading(false);
    }
  }, []);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      handleFileUpload(file);
    }
  };

  const handleDrop = useCallback((event: React.DragEvent) => {
    event.preventDefault();
    setDragOver(false);
    
    const file = event.dataTransfer.files[0];
    if (file) {
      handleFileUpload(file);
    }
  }, [handleFileUpload]);

  const handleDragOver = (event: React.DragEvent) => {
    event.preventDefault();
    setDragOver(true);
  };

  const handleDragLeave = () => {
    setDragOver(false);
  };

  const renderTable = (sheet: ExcelData) => {
    const maxRows = Math.min(sheet.rows.length, 1000); // 限制显示行数以提高性能
    
    return (
      <div className="overflow-auto max-h-[600px]">
        <Table>
          <TableHeader>
            <TableRow>
              {sheet.headers.map((header, index) => (
                <TableHead key={index} className="whitespace-nowrap min-w-[100px]">
                  {header || `列 ${index + 1}`}
                </TableHead>
              ))}
            </TableRow>
          </TableHeader>
          <TableBody>
            {sheet.rows.slice(0, maxRows).map((row, rowIndex) => (
              <TableRow key={rowIndex}>
                {sheet.headers.map((_, cellIndex) => (
                  <TableCell key={cellIndex} className="whitespace-nowrap">
                    {row[cellIndex]?.toString() || ''}
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </TableBody>
        </Table>
        {sheet.rows.length > maxRows && (
          <div className="p-4 text-center text-muted-foreground">
            显示前 {maxRows} 行，共 {sheet.rows.length} 行数据
          </div>
        )}
      </div>
    );
  };

  if (loading) {
    return (
      <Card className="w-full">
        <CardContent className="flex items-center justify-center p-8">
          <div className="text-center">
            <FileSpreadsheet className="h-8 w-8 mx-auto mb-2 animate-pulse" />
            <p>正在解析Excel文件...</p>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!excelData) {
    return (
      <Card className="w-full">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Upload className="h-5 w-5" />
            Excel 文件上传
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div 
            className={`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${
              dragOver ? 'border-primary bg-primary/5' : 'border-gray-300'
            }`}
            onDrop={handleDrop}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
          >
            <FileSpreadsheet className="h-12 w-12 mx-auto mb-4 text-gray-400" />
            <div className="space-y-2">
              <p className="text-lg font-medium">上传 Excel 文件</p>
              <p className="text-gray-500">拖拽文件到这里或点击选择文件</p>
            </div>
            <div className="mt-4">
              <Label htmlFor="file-upload">
                <Button variant="outline" className="cursor-pointer">
                  选择文件
                </Button>
              </Label>
              <Input
                id="file-upload"
                type="file"
                accept=".xlsx,.xls"
                onChange={handleFileChange}
                className="hidden"
              />
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="w-full">
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle className="flex items-center gap-2">
            <FileSpreadsheet className="h-5 w-5" />
            {excelData.filename}
          </CardTitle>
          <Badge variant="secondary">
            {excelData.sheets.length} 个工作表
          </Badge>
        </div>
      </CardHeader>
      <CardContent>
        {excelData.sheets.length === 1 ? (
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-medium">{excelData.sheets[0].sheetName}</h3>
              <Badge variant="outline">
                {excelData.sheets[0].rows.length} 行 × {excelData.sheets[0].headers.length} 列
              </Badge>
            </div>
            {renderTable(excelData.sheets[0])}
          </div>
        ) : (
          <Tabs defaultValue={excelData.sheets[0]?.sheetName} className="space-y-4">
            <TabsList className="grid w-full grid-cols-auto overflow-x-auto">
              {excelData.sheets.map((sheet) => (
                <TabsTrigger key={sheet.sheetName} value={sheet.sheetName} className="whitespace-nowrap">
                  <div className="flex items-center gap-2">
                    <span>{sheet.sheetName}</span>
                    <Badge variant="secondary" className="text-xs">
                      {sheet.rows.length}
                    </Badge>
                  </div>
                </TabsTrigger>
              ))}
            </TabsList>
            
            {excelData.sheets.map((sheet) => (
              <TabsContent key={sheet.sheetName} value={sheet.sheetName} className="space-y-4">
                <div className="flex items-center justify-between">
                  <h3 className="text-lg font-medium">{sheet.sheetName}</h3>
                  <Badge variant="outline">
                    {sheet.rows.length} 行 × {sheet.headers.length} 列
                  </Badge>
                </div>
                {renderTable(sheet)}
              </TabsContent>
            ))}
          </Tabs>
        )}
        
        <div className="mt-4 pt-4 border-t">
          <Button
            variant="outline"
            onClick={() => setExcelData(null)}
            className="mr-2"
          >
            重新上传
          </Button>
        </div>
      </CardContent>
    </Card>
  );
} 